<?php
namespace  App\Http\Controllers\Radius;
use  App\Http\Controllers\Controller;

use App\Model\Rad_line;
use App\Order;

use App\Teamqq;
use Illuminate\Http\Request;

use App\Common\ErrorDefine;

use App\Radacct;
use App\Radcheck;
use App\Radgroupcheck;
use App\Radreply;
use App\Radusergroup;
use App\Rad_manage;


use App\Radgroupreply;
use App\Rad_users;
use App\Rad_order;
use App\Line;
use DB;

use App\Agent;


use App\External_line;

use App\Http\Controllers\Radius\ModuleController;


class  LiuGongController extends Controller
{



    var $module;
    var $accessKeyId = 'LTAI77Yqw1AYSjcC';
    var $accessSecrec = 'fwnMvw1ZJWSWiP2chfulqwqa1F1THJ';


    public function __construct()
    {
        $this->module = new ModuleController();
        date_default_timezone_set("GMT");
    }



    /**
     *获取线路列表
     */
    public function getRegionLineList(Request $request)
    {

        $region = '';
        $page_no = 0;
        $page_size = 30;

        $region =   $request->input('region');
        if($request->input('page_no'))
        {
            $page_no  = $request->input('page_no');
            if($page_no){
                $page_no = $page_no - 1;
                if(is_numeric($page_no)){
                    if($page_no<0){
                        $page_no = 0;
                    }
                }
            }
        }

        if($request->input('page_size'))
        {
            $page_size = $request->input('page_size');
            if($page_size){
                if($page_size <=0 ){
                    $page_size =  20;
                }
            }
        }


        $list = External_line::where(DB::Raw("CONCAT(province,city)"),'like',"%$region%" )->orderBy('created_at','desc')
            ->get(['id','server_address','province','city','created_at','enable_flag','operator'])->toArray();


        $count = count($list);
        $total = ceil($count/$page_size);

        $arr = array_slice($list,$page_size*$page_no,$page_size);

        $data = ['count'=>$count,'page_total'=>$total,'list'=>$arr];

        self::ShowMessage($data);
    }




    /**
     * @param Request $request
     * 添加线路
     */
    public function AddRegionLine(Request $request)
    {

//        判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('token') || empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $user = self::getTokenById($token);

        //  检测用户权限
        if($user[0]['level'] != 2)
        {
            self::ShowError(ErrorDefine::PERMISSION_DENIED);
            return;
        }

        $where = [];

        if(!$request->has('ip') || empty($request->input('ip')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $where['server_address'] = $request->input('ip').'.niumoip.com';


        if(!$request->has('province') || empty($request->input('province')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $where['province'] = $request->input('province');

        if(!$request->has('city') || empty($request->input('city')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $where['city'] = $request->input('city');




        $lines = External_line::where($where)->first();

        if($lines != NULL)
        {
            self::ShowError(ErrorDefine::REGION_LINE_EXISTS);
            return;
        }


        if(!$request->has('operator') || empty($request->input('operator')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $where['operator'] = $request->input('operator');



        External_line::insertGetId($where);

        return self::ShowMessage();



    }




    /**
     *修改线路信息
     */
    public function modifyRegionLine(Request $request)
    {
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }


        //   开户人的 token
        if(!$request->has('token') || empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');


        //   get manage userId
        $user = self::getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }


        //  管理理员权限
        if($user[0]['level'] != 2)
        {
            return self::ShowError(ErrorDefine::PERMISSION_DENIED);
        }


        if(!$request->has('id') || empty($request->input('id')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }


        $id = $request->input('id');


        $liu = External_line::find($id);


        if($request->has('enable_flag'))
        {
            $liu->enable_flag = (int)$request->input('enable_flag');
        }


        if($request->has('ip') && !empty($request->input('ip')))
        {
            $liu->server_address = $request->input('ip');
        }

        if($request->has('province') && !empty($request->input('province')))
        {
            $liu->province = $request->input('province');
        }

        if($request->has('city') && !empty($request->input('city')))
        {
            $liu->city = $request->input('city');

        }

        if($request->has('operator') && !empty($request->input('operator')))
        {
            $liu->operator = $request->input('operator');

        }


        $liu->save();


        return self::ShowMessage();


    }


    /**
     *删除线路
     */
    public function RemoveRegionLine(Request $request)
    {
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }


        //   开户人的 token
        if(!$request->has('token') || empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');


        //   get manage userId
        $user = self::getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }


        //  管理理员权限
        if($user[0]['level'] != 2)
        {
            return self::ShowError(ErrorDefine::PERMISSION_DENIED);
        }


        if(!$request->has('id') || empty($request->input('id')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $where['id'] = $request->input('id');

        if(!$request->has('ip') || empty($request->input('ip')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $where['server_address'] = $request->input('ip');

        $line = External_line::where($where)->first();

        if($line == NULL)
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $ret = $line->delete();
        return self::ShowMessage();


    }











    /**
     *
     * 获取解析记录列表
     */
    public function DescribeDomainRecords()
    {
        $requestParams = array(
            "Action"    =>  "DescribeDomainRecords",
            "DomainName"    =>  "weji.vip"
        );
        return  $this->requestAli($requestParams);
    }



    /**
     * @return mixed
     * 获取子域名的解析记录列表
     */
    public function DescribeSubDomainRecords()
    {
        $requestParams = array(
            "Action"    =>  "DescribeSubDomainRecords",
            "SubDomain"    =>  "xxoo.weji.vip"
        );
        return  $this->requestAli($requestParams);
    }


    /**
     * @param $prefix
     * @return mixed
     * 添加解析记录
     */

    public function AddDomainRecord($prefix)
    {
        $requestParams = array(
            "Action"    =>  "AddDomainRecord",
            "DomainName"    =>  "weji.vip",
            "RR"    =>  $prefix,
            "Type"    =>  "CNAME",
            "Value"    =>  $prefix.".weji.vip",
        );



//        $requestParams = array(
//            "Action"    =>  "AddDomainRecord",
//            "DomainName"    =>  "weji.vip",
//            "RR"    =>  "zz",
//            "Type"    =>  "A",
//            "Value"    =>  "123.56.23.4",
//        );

        return  $this->requestAli($requestParams);
    }





    /**
     * @param $requestParams
     * @return mixed
     * 封装请求
     */
    private function requestAli($requestParams)
    {
        $publicParams = array(
            "Format"        =>  "JSON",
            "Version"       =>  "2015-01-09",
            "AccessKeyId"   =>  $this->accessKeyId,
            "Timestamp"     =>   date("Y-m-d\TH:i:s\Z"),
            "SignatureMethod"   =>  "HMAC-SHA1",
            "SignatureVersion"  =>  "1.0",
            "SignatureNonce"    =>  substr(md5(rand(1,99999999)),rand(1,9),14),
        );

        $params = array_merge($publicParams, $requestParams);
        $params['Signature'] =  $this->sign($params, $this->accessSecrec);
        $uri = http_build_query($params);
        $url = 'http://alidns.aliyuncs.com/?'.$uri;
        return $this->curl($url);
    }






    /**
     * @param $url
     * @return mixed
     * curl 发送
     */
    private function curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        $result=curl_exec ($ch);
        return $result;
    }


    /**
     * @param $params
     * @param $accessSecrec
     * @param string $method
     * @return string
     * 签名
     */
    private function sign($params, $accessSecrec, $method="GET")
    {
        ksort($params);
        $stringToSign = strtoupper($method).'&'.$this->percentEncode('/').'&';

        $tmp = "";
        foreach($params as $key=>$val){
            $tmp .= '&'.$this->percentEncode($key).'='.$this->percentEncode($val);
        }
        $tmp = trim($tmp, '&');
        $stringToSign = $stringToSign.$this->percentEncode($tmp);

        $key  = $accessSecrec.'&';
        $hmac = hash_hmac("sha1", $stringToSign, $key, true);

        return base64_encode($hmac);
    }


    /**
     * @param null $value
     * @return mixed|string
     * 字符编码
     */
    private function percentEncode($value=null)
    {
        $en = urlencode($value);
        $en = str_replace("+", "%20", $en);
        $en = str_replace("*", "%2A", $en);
        $en = str_replace("%7E", "~", $en);
        return $en;
    }



    private function outPut($msg)
    {
        echo date("Y-m-d H:i:s")."  ".$msg.PHP_EOL;
    }










    static function getTokenById($token)
    {
        $user = Rad_manage::where('token',$token)->get()->toArray();
        return $user;
    }










}